package com.konka.spring.framework.webmvc.servlet;

import java.io.File;

/**
 * @author konka
 * @date 2023/2/10
 * @description:
 */
public class ViewResolver {

    private final String DEFAULT_TEMPLATE_SUFFIX = ".html";

    private File templateRootDir;

    public ViewResolver(String templateRootDir) {
        String path = this.getClass().getClassLoader().getResource(templateRootDir).getFile();
        this.templateRootDir = new File(path);
    }

    /**
     * 解析视图名称（处理后缀）
     * @param viewName
     * @return
     */
    public View resolveViewName(String viewName){
        if (viewName ==null || "".equals(viewName.trim())){return null;}

        viewName = viewName.endsWith(DEFAULT_TEMPLATE_SUFFIX) ? viewName : viewName + DEFAULT_TEMPLATE_SUFFIX;

        File templateFile = new File((this.templateRootDir.getPath() + "/" + viewName).replaceAll("/+", "/"));

        return new View(templateFile);
    }
}
